<template>
    <div class="approval-container">
      <!-- 搜索条件区域 -->
      <div class="search-wrapper">
        <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form" label-width="85px" style="text-align: left">
          <div>
            <el-row>
              <el-col :span="5">
                <el-form-item label="食材编号" prop="ingredientsCode">
                  <el-input v-model="searchForm.ingredientsCode" placeholder="食材编号" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="食材名称" prop="ingredientsName">
                  <el-input v-model="searchForm.ingredientsName" placeholder="食材名称" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="供应商名称" prop="supplierName">
                  <el-select
                    v-model="searchForm.supplierId"
                    placeholder="请选择供应商"
                    style="width: 100%"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in supplierList"
                      :key="item.id"
                      :label="item.supplierName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="日期范围" prop="dateRange">
                  <el-date-picker
                    v-model="searchForm.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    style="width: 270px;height: 32px;border-radius: 8px;"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="2" style="text-align: right;">
                <div class="search-actions">
                  <el-button style="background-color: #4C6EE2;color: white;" size="small" @click="handleSearch">搜索</el-button>
                  <el-button size="small" @click="resetSearch">重置</el-button>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
  
      <!-- 操作按钮 -->
      <div class="status-filter" style="display: flex;justify-content: space-between;">
        <div></div>
        <div>
          <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出</el-button>
        </div>
      </div>
  
      <!-- 数据表格 -->
      <div class="table-wrapper">
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading"
          :header-cell-style="{ background: '#f8f8f9' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center"></el-table-column>
          <el-table-column prop="ingredientsCode" label="食材编号"></el-table-column>
          <el-table-column prop="ingredientsName" label="食材名称" align="left"></el-table-column>
          <el-table-column prop="supplierName" label="供应商名称" align="left"></el-table-column>
          <el-table-column prop="stockNum" label="库存" align="left"></el-table-column>
          <el-table-column prop="unit" label="单位" align="left">
            <template slot-scope="scope" v-if="scope.row.unit">
              <!-- {{ scope.row.unit }} -->
              {{ dict.type.foot_ingredient_type.filter(el=>el.value == scope.row.unit)[0].label }}

            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" align="left">
            <template slot-scope="scope">
              ¥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="price" label="采购数量" align="left">
            <template slot-scope="scope">
              {{ Number(scope.row.saleNum) }}
              <!-- {{ scope.row.unit }} -->
              {{ dict.type.foot_ingredient_type.filter(el=>el.value == scope.row.unit)[0].label }}

            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination">
          <pagination v-show="pagination.total > 0" :total="pagination.total" :page.sync="pagination.pageNum" :limit.sync="pagination.pageSize" @pagination="fetchData" />
        </div>
      </div>
      
      <!-- 导出弹窗 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="deriveVisible"
        width="600px"
        @close="deriveVisible = false"
      >
        <template #title>
          <div class="custom-dialog-title">
            <div style="display: flex;border-bottom: 1px solid rgba(0, 0, 0, 0.05);padding-bottom: 20px;padding-left: 30px;">
              <div style="background-color: #4C6EE2;border-radius: 20px;width: 4px;margin-right: 8px;height: 20px;margin-top: 6.5px;"></div>
              <span class="title-text" style="font-family: Source Han Sans;font-size: 20px;font-weight: 500;line-height: 31px;text-align: center;letter-spacing: normal;color: #3D3D3D;">导出订单</span>
            </div>
          </div>
        </template>
<!--   
        <div style="display: flex;justify-content: space-between">
          <div>
            <img src="@/assets/images/reservation.png" style="width: 539px;height: 224px;" alt="">
            <div style="text-align: center;margin-top: 20px;">
              <el-radio v-model="deriveRadio" label="2">待采购清单</el-radio>
            </div>
          </div>
        </div> -->
  
        <div style="margin-top: 20px;display: flex;">
          <div>
            <span style="color: black;font-size: 16px;">导出时间：</span>
            <el-date-picker
              v-model="exportTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              format="yyyy 年 MM 月 dd 日"
              size="mini" 
              value-format="yyyy-MM-dd"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
        </div>
  
        <div slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button @click="deriveVisible = false" style="background-color: white;color: #4C6EE2;border: 1px solid #4C6EE2;">取 消</el-button>
          <el-button type="primary" @click="exportConfirmed" style="background-color: #4C6EE2;color: white;">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { getListDai as getList, deleteIngredient } from '@/api/ingredient'
  import { listData } from '@/api/customer/supplier'
  
  export default {
    name: "ingredient",
    dicts: ['foot_ingredient_type',"food_eat_type"],
    data() {
      const nextWeekRange = this.getNextWeekRange()
      
      return {
        eatType:"1",
        deriveRadio: "2",
        exportTime: [
          nextWeekRange.startDate,
          nextWeekRange.endDate,
        ],
        dialogTitle:"导出",
        deriveVisible:false,
        supplierList:[],
        searchForm: {
          ingredientsCode: '',
          ingredientsName: '',
          supplierId: '',
          dateRange: [nextWeekRange.startDate, nextWeekRange.endDate]
        },
        loading: false,
        tableData: [],
        multipleSelection: [],
        pagination: {
          pageNum: 1,
          pageSize: 10,
          total: 0
        },
        nextWeekRange: nextWeekRange
      }
    },
    created() {
      this.fetchData()
      this.glsList()
    },
    methods: {
      exportConfirmed() {
        if (!this.exportTime || this.exportTime.length !== 2) {
          this.$message.warning('请选择完整的导出时间范围');
          return;
        }
  
        const startDate = new Date(this.exportTime[0]);
        const endDate = new Date(this.exportTime[1]);
        const diffTime = Math.abs(endDate - startDate);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
  
        if (diffDays > 7) {
          this.$message.warning('导出时间范围不能超过7天');
          return;
        }
  
        this.download(`food/ingredients/treat/list/excel`, {
          beginDate: this.exportTime[0],
          endDate: this.exportTime[1],
        }, `清单导出${new Date().toISOString().slice(0, 10)}.xlsx`);
      },
      
      // 获取下周一到周日的时间范围
      getNextWeekRange() {
        const today = new Date()
        const nextMonday = new Date(today)
        // 计算到下周一的天数 (1-7表示周一到周日)
        const daysUntilNextMonday = (1 - today.getDay() + 7) % 7 || 7
        nextMonday.setDate(today.getDate() + daysUntilNextMonday)
        
        const nextSunday = new Date(nextMonday)
        nextSunday.setDate(nextMonday.getDate() + 6)
        
        return {
          startDate: this.formatDate(nextMonday),
          endDate: this.formatDate(nextSunday)
        }
      },
      
      // 格式化日期为YYYY-MM-DD
      formatDate(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      },
      
      // 获取供应商列表
      async glsList() {
        const res = await listData({
          pageNum:1,
          pageSize: 99999999
        })
        this.supplierList = res.rows
      },
      
      // 获取食材列表
      async fetchData() {
        this.loading = true
        try {
          const params = {
            ...this.searchForm,
            ...this.pagination,
            beginDate: this.searchForm.dateRange ? this.searchForm.dateRange[0] : this.nextWeekRange.startDate,
            endDate: this.searchForm.dateRange ? this.searchForm.dateRange[1] : this.nextWeekRange.endDate
          }
          // 删除dateRange字段，避免传给后端
          delete params.dateRange
          
          const data = await getList(params)
          this.tableData = data.rows
          this.pagination.total = data.total
        } catch (error) {
          console.error(error)
        } finally {
          this.loading = false
        }
      },
      
      // 搜索
      handleSearch() {
        this.pagination.pageNum = 1
        this.fetchData()
      },
      
      // 重置搜索
      resetSearch() {
        this.$refs.searchForm.resetFields()
        // 重置日期范围为下周
        this.searchForm.dateRange = [this.nextWeekRange.startDate, this.nextWeekRange.endDate]
        this.handleSearch()
      },
      
      // 多选
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      
      // 导出
      handleExport() {
        this.deriveVisible = true;
      },
      
      // 删除
      handleDelete(row) {
        this.$confirm(`确定删除食材【${row.ingredientsName}】吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await deleteIngredient(row.ingredientsId)
            this.$message.success('删除成功')
            this.fetchData()
          } catch (error) {
            this.$message.error('删除失败')
          }
        }).catch(() => {})
      },
      
      // 批量删除
      handleBatchDelete() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请至少选择一条记录')
          return
        }
        const names = this.multipleSelection.map(item => item.ingredientsName).join('、')
        this.$confirm(`确定删除选中的${this.multipleSelection.length}条记录吗?【${names}】`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const ids = this.multipleSelection.map(item => item.ingredientsId).join(',')
            await deleteIngredient(ids)
            this.$message.success('批量删除成功')
            this.fetchData()
          } catch (error) {
            this.$message.error('删除失败')
          }
        }).catch(() => {})
      }
    }
  }
  </script>
  
  <style scoped>
  ::v-deep .el-dialog{
    border-radius: 10px;
  }
  /* 保持原有样式不变 */
  .approval-container {
    padding: 20px;
    background: #fff;
  }
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-row {
    display: flex;
    margin-bottom: 15px;
  }
  
  .search-row .el-form-item {
    margin-right: 20px;
    margin-bottom: 0;
  }
  
  .search-actions {
    margin-left: auto;
  }
  
  .status-filter {
    margin-bottom: 15px;
  }
  
  .table-wrapper {
    margin-top: 20px;
  }
  
  .content-cell {
    padding: 5px 0;
  }
  
  .content-cell p {
    margin: 5px 0;
    line-height: 1.5;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .el-table::before {
    display: none;
  }
  
  .el-table {
    border: none;
  }
  
  .el-table /deep/ th {
    border-bottom: 1px solid #ebeef5;
  }
  
  .el-table /deep/ td {
    border-bottom: 1px solid #ebeef5;
  }
  
  .el-input-number {
    width: 100%;
  }
  
  ::v-deep .el-radio__input.is-checked .el-radio__inner {
    background-color: #4C6EE2;
    border: 1px solid #4C6EE2;
    color: black;
  }
  
  ::v-deep .el-radio__input.is-checked + .el-radio__label {
    color: black;
  }
  
  ::v-deep .el-form-item {
    margin-bottom: 8px;
    margin-right:0;
  }
  
  ::v-deep .el-input--medium .el-input__inner {
    height: 32px;
    line-height: 32px;
    border-radius: 8px;
    background: rgba(0, 0, 0, 0);
    box-sizing: border-box;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }
  </style>